﻿
jQuery(function () {
    getCateA1Data();
});
function getAllInput() {
    var datas = [];
    var data = {};
    jQuery("#searchFilter :input").each(function () {
        var input = jQuery(this); // This is the jquery object of the input, do what you will
        var name = jQuery(input).attr("id");
        var type = jQuery(input).attr("type");
        if (name != undefined) {
            if (type != undefined && type == 'checkbox') {
                if (jQuery('#' + name).is(":checked"))
                {
                    data[name] = jQuery('#' + name).val();
                }
            }
            else {
                var value;
                if (name == "datefrom" || name == "dateto") {
                    value = jQuery('#' + name).datetimebox('getValue')
                }
                else {
                    value = jQuery('#' + name).val();
                }
                data[name] = value;
            }
        }
    });
    datas.push(data);
    return datas;
}

function getCateA1Data() {
    var container = jQuery('#checkbokItem');
    var checkboxAll = '';
    jQuery.ajax({
        url: "/api.ashx?metdhodName=getta1catewithSection3",
        type: "GET",
        cache: false,
        async: false,
        dataType: "json",
        success: function (d) {
            if (d.length != 0) {
                jQuery.each(d, function (i, d2) {
                    checkboxAll += "<div style='float:left; margin-right:10px;vertical-align:middle'><input style='margin-right:3px;' type='checkbox' text='" + d2.a1CateName + "' id='cb" + d2.a1CateId + "' value=" + d2.a1CateId + " /><span style='margin-top:3px;'>" + d2.a1CateName + "</span></div>";

                });
                container.html(checkboxAll);
            }

           

        },
        error: function (d) {
            alert('ไม่มีข้อมูลรายงานในส่วนนี้');
        }
    });
}

function DoSearch(searchparam) {
    var searchParam = [];
    if (searchparam != undefined) {
        searchParam = searchparam;
    }
    else {
        searchParam = getAllInput();
    }
    var data2 = JSON.stringify(searchParam);
    jQuery.ajax({
        url: "/api.ashx?metdhodName=doSearch",
        data: { postData: data2 },
        type: "GET",
        cache: false,
        async: true,
        dataType: "json",
        success: function (result) {
            jQuery('#dg').datagrid('loadData', result);
            jQuery('#dg').datagrid({
                onDblClickRow: function (index, fields) {
                    editDocument(status, fields);
                    getScoreSelect();
                }
            });

        }
    });
}


function getScoreSelect(isUser) {
    score = 0;
    cash = 0;
    if (isUser) {
        jQuery('#userDiv #tableMeasurement input:radio:checked').each(function (i, i2) {
            score += parseInt(jQuery(i2).val());
            jQuery('#userDiv #totolScore').text(score);
        });
    }
    else {
        jQuery('#approver1Div #tableMeasurement input:radio:checked').each(function (i, i2) {
            score += parseInt(jQuery(i2).val());
            jQuery('#approver1Div #totolScore').text(score);
        });
    }

    jQuery('[class^=score]').removeClass('datagrid-row-selected');
    if (score > 3 && score <= 8) {
        jQuery('.score1').addClass('datagrid-row-selected');
        cash = 20;
    }
    else if (score > 8 && score <= 12) {
        jQuery('.score2').addClass('datagrid-row-selected');
        cash = 40;
    }
    else if (score > 12 && score <= 16) {
        jQuery('.score3').addClass('datagrid-row-selected');
        cash = 60;
    }
    else if (score > 16 && score <= 18) {
        jQuery('.score4').addClass('datagrid-row-selected');
        cash = 100;
    }
    else if (score > 18) {
        jQuery('.score5').addClass('datagrid-row-selected');
        cash = 300;
    }

}

function DoQuickSearch(searchparam) {
    var quicksearchText = jQuery('#quicksearchText').val();
  
       jQuery.ajax({
        url: "/api.ashx?metdhodName=doQuickSearch",
        data: { postData: quicksearchText },
        type: "GET",
        cache: false,
        async: true,
        dataType: "json",
        success: function (result) {
            jQuery('#dg').datagrid('loadData', result);
            jQuery('#dg').datagrid({
                onDblClickRow: function (index, fields) {
                    editDocument(status, fields);
                    getScoreSelect();
                }
            });

        }
    });
}

function showSearchDetail() {
    jQuery('#quicksearchFilter').hide();
    jQuery('#searchFilter').show();
    jQuery('#showSearchDetail').hide();
    jQuery('#hideSearchDetail').show();
    

}

function hideSearchDetail() {
    jQuery('#quicksearchFilter').show();
    jQuery('#searchFilter').hide();
    jQuery('#showSearchDetail').show();
    jQuery('#hideSearchDetail').hide();
}

function ExportSearch() {

    //var querySearch = "";
    var searchParam = getAllInput();
    var data = {};
    data["Location"] = jQuery('#location').val();
    searchParam.push(data); 
    var data2 = JSON.stringify(searchParam);
    var uri = "/api.ashx?metdhodName=doSearch&iscsv=true&postData=" + data2;
    window.open(uri);
}
function ExportExcel() {
    var searchParam = getAllInput();
    var data = {};
    data["Location"] = jQuery('#location').val();
    searchParam.push(data);
    var data2 = JSON.stringify(searchParam);
    var uri = "/api.ashx?metdhodName=saveExcel&postData=" + data2;
    window.open(uri);
}

function ExportExcelTechno() {
    var searchParam = getAllInput();
    var data = {};
    data["Location"] = jQuery('#location').val();
    data["DivName"] = "technologyry";
    searchParam.push(data);
    var data2 = JSON.stringify(searchParam);
    var uri = "/api.ashx?metdhodName=saveExcel&postData=" + data2;
    window.open(uri);
}

function editDocument(status, rowselect) {
    var row = jQuery('#dg').datagrid('getSelected');
    if (row) {
        //jQuery.uniform.restore(jQuery('select, input:checkbox'));
        jQuery('#fmA1').form('clear');
        jQuery('#UploadedFileA1').html('');
        jQuery('#UploadedFileA1After').html('');

        //jQuery('select, input:checkbox').uniform();
        jQuery('#dlgA1').dialog('open').dialog('setTitle', 'อนุมัติแบบฟอร์ม');
        jQuery('#fmA1').form('load', row);
        //jQuery.uniform.restore(jQuery('select, input:checkbox'));
        jQuery.post('/api.ashx?metdhodName=getdocPropbyID', { id: row.id }, function (result) {
            var json = jQuery.parseJSON(result);
            var data = {};
            jQuery.each(json, function (index, d) {

                if (d.dataDate != null || d.dataDate != undefined) {
                    data[d.propertyName] = d.dataDate;
                }
                if (d.dataDecimal != null || d.dataDecimal != undefined) {
                    data[d.propertyName] = d.dataDecimal;
                }
                if (d.dataInt != null || d.dataInt != undefined) {
                    data[d.propertyName] = d.dataInt;
                }
                if (d.dataNtext != null || d.dataNtext != undefined) {
                    data[d.propertyName] = d.dataNtext;
                }
                if (d.dataNvarchar != null || d.dataNvarchar != undefined) {
                    if (d.dataNvarchar.toLowerCase() == 'true') {
                        if (d.propertyName >= 1000) {
                            jQuery('#' + d.propertyName + 'a1').prop('checked', true);
                        }
                        else {
                            jQuery('#approver1Div :input[id=' + d.propertyName + ']').prop('checked', true);
                        }
                        //jQuery('#' + d.propertyName).prop('checked', true);
                    }
                    else if (d.dataNvarchar.toLowerCase() == 'false') {
                        if (d.propertyName >= 1000) {
                            jQuery('#' + d.propertyName + 'a1').prop('checked', false);
                        }
                        else {
                            jQuery('#approver1Div :input[id=' + d.propertyName + ']').prop('checked', false);
                        }

                        //jQuery('#' + d.propertyName).prop('checked', false);

                    }
                    else {
                        if (d.propertyName == 'docImage') {
                            var filename = d.dataNvarchar.substr(d.dataNvarchar.lastIndexOf("/") + 1);
                            jQuery("<a id='" + d.id + "' " + "class='preview imageuploaded' target='_blank' ' href='" + d.dataNvarchar + "'>" + filename + " </a>").appendTo('#UploadedFileA1');
                        }
                        else if (d.propertyName == 'docImageAfter') {
                            var filename = d.dataNvarchar.substr(d.dataNvarchar.lastIndexOf("/") + 1);
                            jQuery("<a id='" + d.id + "' " + "class='preview imageuploaded' target='_blank' ' href='" + d.dataNvarchar + "'>" + filename + " </a>").appendTo('#UploadedFileA1After');
                        }
                        else if (d.propertyName == 'approverType') {
                            jQuery('#approver2Div :input:radio[name=approverType]').filter('[value=' + d.dataNvarchar + ']').prop('checked', true)

                            //jQuery('#approver2Div :input :radio[name=' + d.propertyName + ']').prop('checked', true);
                        }
                        else {
                            data[d.propertyName] = d.dataNvarchar;
                        }
                    }
                }
            });

            jQuery('#fmA1').form('load', data);
            jQuery('#approver1Div').form('load', data);
            jQuery('#approver2Div').form('load', data);

            //jQuery('select, input:checkbox').uniform();
            imagePreview();
            jQuery("form#fmA1 :input").attr("disabled", true);
            jQuery("#userDiv :input").attr("disabled", true);
            jQuery("#approver1Div :input").attr("disabled", true);
            jQuery("#approver2Div :input").attr("disabled", true);
            jQuery("#approverTQMDiv :input").attr("disabled", true);

            jQuery("#UploadButton").hide();
            jQuery("#userDiv").show();
            
        });
        //urlTag = '/api.ashx?metdhodName=editTag&id=' + row.tagId;
    }
}

function JSON2CSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

    var str = '';
    var line = '';

    if (jQuery("#labels").is(':checked')) {
        var head = array[0];
        if (jQuery("#quote").is(':checked')) {
            for (var index in array[0]) {
                var value = index + "";
                line += '"' + value.replace(/"/g, '""') + '",';
            }
        } else {
            for (var index in array[0]) {
                line += index + ',';
            }
        }

        line = line.slice(0, -1);
        str += line + '\r\n';
    }

    for (var i = 0; i < array.length; i++) {
        var line = '';

        if (jQuery("#quote").is(':checked')) {
            for (var index in array[i]) {
                var value = array[i][index] + "";
                line += '"' + value.replace(/"/g, '""') + '",';
            }
        } else {
            for (var index in array[i]) {
                line += array[i][index] + ',';
            }
        }

        line = line.slice(0, -1);
        str += line + '\r\n';
    }
    return str;

}
